package com.itheima.shop.web.servlet;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.lang.reflect.Method;

/**
 * 所有Servlet继承此类
 */
public class BaseServlet extends HttpServlet {

    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.setCharacterEncoding("utf-8");
        resp.setContentType("text/html;charset=utf-8");
        String action = req.getParameter("action");
        try {
            if (action != null && action.length() > 0) {
                //通过参数名获取对应请求servlet中的方法
                Method method = this.getClass().getDeclaredMethod(action, HttpServletRequest.class, HttpServletResponse.class);
                method.setAccessible(true);
                method.invoke(this, req, resp);
            } else {
                System.out.println("BaseServlet未接收到action参数");
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
